//app.js
var auth = require('./utils/auth.js')
var mbrService = require('./api/memberService.js')
var sysService = require('./api/systemService.js')

App({

  onLaunch: function () {
    wx.hideTabBar();
    this.getSystemOptions();
    // 取当前用户    
    this.globalData.userInfo = auth.getUser();

    this.refreshAccessToken();
    try {
      const res = wx.getSystemInfoSync()
      this.globalData.systemInfo = res
    } catch (e) {
      // Do something when catch error
    }
    // 隐藏会员信息
    // this.globalData.userInfo = {
    //   ...this.globalData.userInfo,
    //   member: null
    // }
    // 展示本地存储能力
    // var logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

  },
  onShow: function (options) {
    // Do something when show.
    console.log(options)
    if (options.scene) {
      var scene = decodeURIComponent(options.query.scene)
      if (scene && scene === 'isfromQR') {
        this.globalData.scene = scene
        try {
          wx.setStorageSync('wj_sceneForm', this.globalData.scene)
        } catch (e) {}
      } else {
        try {
          var scene = wx.getStorageSync('wj_sceneForm')
          if (scene && scene === 'isfromQR') {
            // Do something with return value
            this.globalData.scene = scene
          }
        } catch (e) {
          // Do something when catch error
        }
      }
    } else {
      let scene = 'isfromQR'
      this.globalData.scene = scene
    }
    wx.hideTabBar();
  },
  onHide: function () {
    // Do something when hide.
    try {
      wx.removeStorageSync('wj_sharingId')
      console.log("------------清除邀请人信息成功")
    } catch (error) {
      console.log(error)
    }
  },

  /**
   * 准备刷新令牌
   */
  refreshAccessToken() {
    var tokens = auth.getTokens();
    if (!tokens || !tokens.expiresTo) {
      this.globalData.userInfo = null
      console.log("当前用户未登录，请先登录")
      return;
    }

    // 如果refresh token也过期，就不再刷新令牌了
    if (tokens.refreshExpiresTo < new Date().getTime()) {
      this.globalData.userInfo = null
      console.log("刷新令牌已经过期，请重新登录")
      return
    }

    // 刷新令牌时间，提前30分钟
    var expiresIn = tokens.expiresTo - new Date().getTime() - 60 * 10 * 1000;
    expiresIn = expiresIn <= 0 ? 1000 : expiresIn;
    setTimeout(function () {
      // 准备刷新令牌
      mbrService.refreshToken(tokens.refreshToken)
        .then(data => {
          auth.setTokens(data)
        })
        .catch(err => {
          console.log(err)
        })
    }, expiresIn);
  },

  /**
   * 查询系统配置项
   */
  getSystemOptions() {
    sysService.query().then(res => {
      console.log(res)
      this.globalData.configureInfo = res
      if (res && res.length > 0) {
        res.forEach(item => {
          if (item.key === 'memberAscriptionStoreDistance' && item.value) {
            this.globalData.systemConfigure.memberAscriptionStoreDistance = item.value
          } else if (item.key === 'appContactMobile' && item.value) {
            this.globalData.servicePhone = item.value
          }
        });
      }
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * 跳转后修改tabbar
   */
  editTabbar: function () {
    wx.hideTabBar();
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    console.log("12")
    _this.setData({
      tabbar: tabbar
    });
  },
  globalData: {
    userInfo: null,
    memberInfo: null,
    addressInfo: null,
    storeInfo: null,
    systemConfigure: {
      hasRedPacket: false,
      memberAscriptionStoreDistance: 1000
    },
    configureInfo: [],
    systemInfo: {},
    servicePhone: '400-881-9090',
    tabBar: {
      "backgroundColor": "#ffffff",
      "color": "#979795",
      "selectedColor": "#1c1c1b",
      "list": [{
          "pagePath": "/pages/mallModule/index/index/index",
          "iconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_home.png",
          "selectedIconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_home_active.png",
          "text": "首页",
        },
        {
          "pagePath": "/pages/mallModule/goods/category/category",
          "iconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_category.png",
          "selectedIconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_category_active.png",
          "text": "分类"
        },
        {
          "pagePath": "/pages/mallModule/goods/search/search",
          "iconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/speechAssistantDefault.gif",
          "selectedIconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/speechAssistantStart.gif",
          "text": "",
          "isSpecial": true,
        },
        {
          "pagePath": "/pages/mallModule/goods/shopcart/shopcart",
          "iconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_shopcart.png",
          "selectedIconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_shopcart_active.png",
          "text": "购物袋"
        },
        {
          "pagePath": "/pages/mallModule/member/my/my",
          "iconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_my.png",
          "selectedIconPath": "https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/tabbar_my_active.png",
          "text": "我的"
        }
      ]
    },
    scene: 'normal'
  }
})